<script setup>
import { getRolePage } from '@/api/auth'
import { getUserPage, banUser, addUserRole, deleteUserRole } from '@/api/user'
import { getDateTimeStr } from '@/utils/formatDate'
import { uniqueArray, compareArrays } from '@/utils/arrutils'
// 每页展示数据条目
const PAGE_SIZE = 10
// 分页查询参数
const userPageMsg = ref({
  pageNum: 1,
  pageSize: PAGE_SIZE,
  avatar: null,
  nickname: null,
  username: null,
  createTimeStartAndEnd: [new Date(2024, 0, 1), new Date(2025, 0, 1)],
  status: null
})
// 分页查询结果
const userPageList = ref([])
// 分页查询条目总数
const userPageTotal = ref(0)

// 角色列表
const roleList = ref([])
// 进入页面后进行一次查询展示
onMounted(async () => {
  const tempRes = await getRolePage({
    pageNum: 1, pageSize: 99, status: 1
  })
  roleList.value = tempRes.list
  await getTableData()
})

// 展示的表格数据
const tableData = ref([])
// 把查询结果映射到表格
const resMsgToTableData = () => {
  tableData.value = []
  for (let i = 0; i < userPageList.value.length; i++) {
    const tempObj = {
      key: userPageList.value[i].id,
      tableIndex: i + 1 + PAGE_SIZE * (userPageMsg.value.pageNum - 1),
      avatar: userPageList.value[i].avatar,
      username: userPageList.value[i].username,
      nickname: userPageList.value[i].nickname,
      createTime: getDateTimeStr(userPageList.value[i].createTime),
      status: userPageList.value[i].status,
      roleList: userPageList.value[i].roleList.map(item => item.roleCode),
      oldRoleList: userPageList.value[i].roleList.map(item => item.roleCode),
      roleAllList: uniqueArray([...userPageList.value[i].roleList, ...roleList.value], 'roleCode').map(item => ({ value: item.roleCode, label: item.roleName }))
    }
    tableData.value.push(tempObj)
  }
}

// 修改页码
const pageChange = async (pageNum) => {
  userPageMsg.value.pageNum = pageNum
  getTableData()
}

// 查询
const getTableData = async () => {
  const tempRes = await getUserPage(userPageMsg.value)
  userPageList.value = tempRes.list
  userPageTotal.value = +tempRes.total
  resMsgToTableData()
}

// 开关封禁用户
const switchChange = async (data) => {
  await banUser({
    id: data.key,
    status: data.status === 1 ? 5 : 1
  })
  data.status = data.status === 1 ? 5 : 1
}

// 修改用户拥有的角色
const updateUserRole = async (record) => {
  const tempItemObj = compareArrays(record.roleList, record.oldRoleList)
  record.oldRoleList = record.roleList
  if (tempItemObj.key) {
    await addUserRole({
      id: record.key,
      roleCode: tempItemObj.item
    })
  } else {
    await deleteUserRole({
      id: record.key,
      roleCode: tempItemObj.item
    })
  }
}
</script>

<template>
  <a-layout class="layout-demo">
    <a-layout-header>
      <!-- 查询参数输入区 start -->
      <div class="box">
        <span class="my-span">用户名称</span>
        <a-input placeholder="请输入用户名称" allow-clear class="my-input"
          v-model="userPageMsg.username" />
      </div>
      <div class="box">
        <span class="my-span">用户昵称</span>
        <a-input placeholder="请输入用户昵称" allow-clear class="my-input"
          v-model="userPageMsg.nickname" />
      </div>
      <div class="box">
        <span class="my-span">创建时间</span>
        <a-range-picker class="my-input"
          style="width: 248px; border: 1px solid rgb(217, 217, 217); box-sizing: border-box;"
          v-model="userPageMsg.createTimeStartAndEnd" :value-format="'Date'" />
      </div>
      <div class="box">
        <a-button class="my-btn" type="outline" @click="getTableData">查询</a-button>
      </div>
      <!-- 查询参数输入区 end -->
    </a-layout-header>
    <a-layout-content>
      <!-- 信息展示表格 start -->
      <a-table :data="tableData" class="my-table" :pagination="false">
        <template #columns>
          <a-table-column :align="'center'" title="序号" data-index="tableIndex" />
          <a-table-column :align="'center'" title="用户头像" data-index="avatar">
            <template #cell="record">
              <a-avatar>
                <img :src="record.record.avatar" />
              </a-avatar>
            </template>
          </a-table-column>
          <a-table-column :align="'center'" title="用户名称" data-index="username" />
          <a-table-column :align="'center'" title="用户昵称" data-index="nickname" />
          <a-table-column :align="'center'" title="创建日期" data-index="createTime" />
          <a-table-column :align="'center'" title="拥有的角色">
            <template #cell="record">
              <div>
                <a-select placeholder="无角色" multiple :max-tag-count="2" :style="{width: 'auto'}"
                  v-model="record.record.roleList" @change="updateUserRole(record.record)">
                  <a-option v-for="item in record.record.roleAllList" :key="item.value"
                    :value="item.value" :label="item.label" />
                </a-select>
              </div>
            </template>
          </a-table-column>
          <!-- 封禁状态开关，1是正常，5是封禁 -->
          <a-table-column :align="'center'" title="封禁状态">
            <template #cell="record">
              <a-switch :checked-value="5" :unchecked-value="1"
                :default-checked="record.record.status === 5 ? true : false"
                @change="switchChange(record.record)" :checked-text="'封禁中'"
                :unchecked-text="'未封禁'" />
            </template>
          </a-table-column>
        </template>
      </a-table>
      <!-- 信息展示表格 end -->
      <!-- 分页器 -->
      <div>
        <a-pagination class="table-end-pagination" :total="userPageTotal" :page-size="PAGE_SIZE"
          @change="pageChange" />
      </div>
    </a-layout-content>
    <a-layout-footer>Footer</a-layout-footer>
  </a-layout>
</template>

<style scoped>
.layout-demo :deep(.arco-layout-header) {
  height: auto;
  display: flex;
  flex-wrap: wrap;
  flex-direction: row;
  align-items: center;
  font-size: 16px;
  font-stretch: condensed;
  text-align: center;
}

.layout-demo :deep(.arco-layout-header) .box {
  display: inline-block;
  margin: 12px 0;
}

.my-btn {
  margin-left: 12px;
}

.layout-demo :deep(.arco-layout-sider) {
  width: 206px;
}

.table-head-div {
  margin-top: 40px;
}

.my-table {
  margin: 64px 64px 0;
}

.table-end-btn,
.table-end-pagination {
  margin: 12px 64px;
}

.table-end-btn {
  float: left;
}

.table-end-pagination {
  float: right;
}

.my-span {
  margin: 0 12px;
}

.my-input {
  width: 128px;
  border: 1px solid #d9d9d9;
}

.tag:nth-child(n + 2) {
  margin-left: 8px;
}
</style>